package org.fastsyncer.plugin.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.plugin.AbstractConvert;
import org.fastsyncer.plugin.impl.pool.DatabasePool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * <ul>
 * <dt>星盾Ldap目录人员信息转换规则：</dt>
 *  <dl>
 *      <li>找到人员所有的岗位</li>
 *  </dl>
 * </ul>
 * 
 * @author AE86
 * @date 2018年03月12日 下午13:46:09
 * @version 1.0.0
 */
public class AostarLdapMiAccountConvertImpl extends AbstractConvert {

    private static final Logger logger = LoggerFactory.getLogger(AostarLdapMiAccountConvertImpl.class);

    /**
     * 根据APP_ID和MI_ID查询应用帐号(类型为业务帐号)的岗位
     * <pre>
     * SELECT M.POST_CODE 
     * FROM SD_MI_ACCOUNT I 
     * INNER JOIN SD_MA_MI_REL R ON(I.ID=R.MI_ID) 
     * INNER JOIN SD_POST_MA_REL P ON(R.MA_ID=P.MA_ID) 
     * INNER JOIN SD_POST_MAINTAIN M ON(P.POST_ID=M.ID) 
     * WHERE I.APP_ID = ? AND I.ID = ? AND I.APPACCOUNT_TYPE = '1'
     * AND R.IS_DELETED = '0' AND P.IS_DELETED = '0'</pre>
     */
    private static final String QUERY_POST_CODE_BY_APP_ID_AND_MI_ID = "SELECT M.POST_CODE FROM SD_MI_ACCOUNT I INNER JOIN SD_MA_MI_REL R ON(I.ID=R.MI_ID) INNER JOIN SD_POST_MA_REL P ON(R.MA_ID=P.MA_ID) INNER JOIN SD_POST_MAINTAIN M ON(P.POST_ID=M.ID) WHERE I.APP_ID = ? AND I.ID = ? AND I.APPACCOUNT_TYPE = '1' AND R.IS_DELETED = '0' AND P.IS_DELETED = '0'";
    
    @Override
    public String getConvertName() {
        return "应用帐号_港中旅目录帐号转换";
    }

    @Override
    public void convert(MappingTask task, List<Map<String, Object>> source, List<Map<String, Object>> target) {
        final int sourceSize = source.size();
        final int targetSize = target.size();
        if (sourceSize != targetSize) {
            return;
        }
        
        // 创建连接池
        DatabasePool pool = DatabasePool.getInstance();
        String uuid = pool.create(task.getSourceMapping());
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        try {
            // 获取数据库连接
            JdbcTemplate jdbc = pool.get(uuid);
            if (null == jdbc) {
                return;
            }
            
            int size = source.size();
            for (int i = 0; i < size; i++) {
                // 设置岗位信息
                this.buildPost(jdbc, source.get(i), target.get(i));
            }
        } catch (Exception e) {
            logger.info(e.getClass() + " >> " + e.getLocalizedMessage());
        } finally {
            pool.close(uuid);
        }
    }

    @Override
    public void convert(MappingTask task, Map<String, Object> source, Map<String, Object> target, String event, Map<String, Object> beforeData) {
        if (null == source || null == target) {
            return;
        }
        
        // 排除删除操作
        if (ConnectorConstant.OPERTION_DELETE.equals(event)) {
            return;
        }
        
        // 创建连接池
        DatabasePool pool = DatabasePool.getInstance();
        String uuid = pool.create(task.getSourceMapping());
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        try {
            // 获取数据库连接
            JdbcTemplate jdbc = pool.get(uuid);
            if (null == jdbc) {
                return;
            }
            // 设置岗位信息
            this.buildPost(jdbc, source, target);
        } catch (Exception e) {
            logger.info(e.getClass() + " >> " + e.getLocalizedMessage());
        } finally {
            pool.close(uuid);
        }
    }
    
    private void buildPost(JdbcTemplate jdbc, Map<String, Object> s, Map<String, Object> t) {
        // 数据源ID
        Object id = s.get("ID");
        Object appid = s.get("APP_ID");
        
        // 根据企业帐号ID查询关联的所有岗位
        List<Map<String, Object>> list = jdbc.queryForList(QUERY_POST_CODE_BY_APP_ID_AND_MI_ID, new Object[]{ appid, id });
        if(null == list || list.isEmpty()){
            t.put("hkcts-dutyNumber", new ArrayList<String>());
            return;
        }
        
        // 取出岗位
        int size = list.size();
        List<String> pos = new ArrayList<String>(size);
        Map<String, Object> row;
        String postCode;
        for (int i = 0; i < size; i++) {
            row = list.get(i);
            postCode = (String) row.get("POST_CODE");
            if(StringUtils.isBlank(postCode)){
                continue;
            }
            pos.add(postCode);
        }
        if(pos.isEmpty()){
            t.put("hkcts-dutyNumber", new ArrayList<String>());
            return;
        }

        // 将岗位集合设置到目标源中
        // 目录岗位属性
        t.put("hkcts-dutyNumber", pos);
    }
    
}
